const { exec, spawn } = require('child_process');
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: process.env.WSPORT || '3005' });
const archiver = require('archiver');
const fs = require('fs');

// 逐行打印日志的方法
async function tospawn(command, args, payload) {
    return new Promise((resolve, reject) => {
        const child = spawn(command, args, payload);

        let stdoutData = '';
        let stderrData = '';

        child.stdout.on('data', (data) => {
            const output = data.toString();
            const lines = output.split('\n');
            lines.forEach(line => {
                broadcastMessage(line);
            });
            stdoutData += output;
        });

        child.stderr.on('data', (data) => {
            const errorOutput = data.toString();
            stderrData += errorOutput;
        });

        child.on('close', (code) => {
            if (code === 0) {
                resolve(stdoutData);
            } else {
                reject(stderrData);
            }
        });

        child.on('error', (err) => {
            reject(err);
        });
    });
}


// 压缩文件夹的函数
async function compressFolder(inputFolder, outputFilePath) {
    return new Promise((resolve, reject) => {
        const output = fs.createWriteStream(outputFilePath);
        const archive = archiver('zip', { zlib: { level: 9 } });

        // 监听错误事件
        archive.on('error', (error) => {
            console.error('压缩文件夹时发生错误:', error);
            reject(error);
        });

        // 监听压缩完成事件
        archive.on('finish', () => {
            console.log('文件夹已成功压缩到:', outputFilePath);
            resolve(outputFilePath);
        });

        // 将压缩流连接到输出流
        archive.pipe(output);

        // 添加文件夹及其内部的所有文件和子文件夹到压缩包
        archive.directory(inputFolder, false);

        // 开始压缩
        archive.finalize();
    });
}

function broadcastMessage(message) {
    wss.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
            client.send(message);
        }
    });
}


const executeCommand = async (command, payload) => {
    // 模拟一个异步操作，比如读取文件或者发送网络请求
    return new Promise((resolve, reject) => {
        exec(command, payload, (error, stdout, stderr) => {
            if (error) {
                reject(error)
                return;
            }
            resolve(stdout)
        });
    });
}


wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('服务端接收到数据：', message);
    });

    ws.on('close', function () {
        console.log('客户端已断开连接');
    });

    ws.on('error', function (error) {
        console.error('WebSocket 错误：', error);
    });
});

module.exports = {
    broadcastMessage,
    executeCommand,
    compressFolder,
    tospawn
};